﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module;
using Cit.CDE.Net.Module;
using cde.SystemCommon;
using Cit.CDE.Net.Service.ModuleFactory;
using Cit.CDE.Net.Module.Commons;
using System.IO;
using System.Text;
using System.Data;
using Cit.CDE.Net.Service;

/// <summary>
/// 课件下载
/// </summary>
public partial class main_course_DownloadCourse : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string cId = Util.objectToString(Page.Request.QueryString["CSW_ID"]);
        if (cId != "")
        {
            cmdDownload(cId);
        }
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void cmdDownload(string id)
    {

        //当前登陆人信息
        LoginOprator op = (LoginOprator)Session[Cit.CDE.Net.Module.Commons.CDEConstants.SESSION_LOIN_OPRATOR];
        //当前时间
        string Now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "/");

        List<CDEEntity> listEntity = new List<CDEEntity>();

        CDEEntityManager courseEm = CDEEMFactory.getEMByFullName("WEB.CSW_MANAGE");
        CDESearchCriteria courseSc = new CDESearchCriteria(courseEm);
        courseSc.addCondition("ID", id);
        List<CDEEntity> courseList = CDEService.LoadEntities(courseEm, courseSc);

        if (courseList.Count > 0)
        {
            CDEEntity m_entity = courseList[0];
            string path = System.Configuration.ConfigurationSettings.AppSettings["Courseware"];
            string file = System.Web.HttpContext.Current.Server.MapPath(path + m_entity.get("CSW_ID").ToString().Trim());
            System.IO.FileInfo myfile = new System.IO.FileInfo(file);
            if (myfile.Exists)
            {
                  if (op != null)
                {             
                    //下载记录
                    courseOperate(id, op.SysID, "0");            
                }

                try
                {
                        long fileSize = myfile.Length; 
                        Response.Clear();
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(m_entity.get("FILE_PATH").ToString().Trim()));
                        Response.AddHeader("Content-Length", fileSize.ToString());
                        Response.ContentType = "application/octet-stream";
                        Response.WriteFile(file, 0, fileSize); 
                        Response.Flush(); 
                        Response.Close();

                }
                 catch (Exception ex)
                {
                    Response.Write("Error:" + ex.Message);
                }
                finally
                {                  
                    Response.Close();
                }
            }
            else
            {
                showMessageErrAndOk("文件未找到，请联系管理员!");
            }
        }
    }

    /// <summary>
    /// 课件操作
    /// </summary>
    /// <param name="id"></param>
    /// <param name="user_id"></param>
    /// <param name="type">0:下载,1:查看</param>
    /// <returns></returns>
    public bool courseOperate(string id, string user_id, string type)
    {

        //每天只记录一次
        StringBuilder sql = new StringBuilder();
//        sql.AppendFormat(@"select id from COURSEWARE_OPERATE where CSW_ID ={0} and user_id={1} and    oper_type={2} and
//                            dbo.DATE_FORMAT(insert_date,'YYYY/MM/DD')=dbo.DATE_FORMAT(getdate(),'YYYY/MM/DD')
//                            ", id, user_id, type);
//        DataTable op_table = Util.loadSql(sql.ToString());
//        if (op_table.Rows.Count != 0)
//        {
//            return false;
//        }

        //操作明细记录
        CDEEntityManager oper_em = CDEEMFactory.getEMByFullName("WEB.CSW_OPERATE");
        CDEEntity oper_entity = CDEEMServiceFactory.getEMService(oper_em).CreateEntity();
        oper_entity.Operation = CDEDataOperation.INSERT;
        oper_entity.set("CSW_ID", id);
        oper_entity.set("USER_ID", user_id);
        oper_entity.set("OPER_TYPE", type);
        List<CDEEntity> listEntity = new List<CDEEntity>();
        listEntity.Add(oper_entity);
        CDEService.UpdateEntities(oper_em, listEntity);
        if (listEntity[0].Result == CDEDataOperationResult.ERROR)
        {
            return false;
        }
        else
        {
            //知识库主表查看数更新
            sql = new StringBuilder();
            sql.AppendFormat(@"update COURSEWARE set DOWNLOADS=DOWNLOADS+1 where id={0}", id);
            Util.ExcSql(sql.ToString());

            return true;
        }
    }

    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMsg"></param>
    protected void showMessageErrAndOk(string strMsg)
    {
        StringBuilder sbr = new StringBuilder();
        sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
        sbr.AppendFormat("alert(\"");
        sbr.AppendFormat(strMsg);
        sbr.AppendFormat("\");</script>{0}", Environment.NewLine);
        Page.ClientScript.RegisterStartupScript(Page.GetType(), "PageStartup", sbr.ToString());

    }
 }
